using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PixelCanvas : MonoBehaviour
{
    public List<Color> palette = new List<Color>();
    public int[,] img = null;

    public int Width => width;
    public int Height => height;
    public int selectedIdx { get; set; }
    public Color selectedColor => palette[selectedIdx];

    private int width, height;
    

    public void InitCanvas(int width, int height)
    {
        palette.Clear();
        palette.Add(new Color(0, 0, 0, 0));
        selectedIdx = 0;
        img = new int[width, height];
        this.width = width;
        this.height = height;
    }

    public int AddColor(Color color)
    {
        int idx = palette.Count;
        palette.Add(color);
        return idx;
    }

    public void SetPixel(int x, int y)
    {
        SetPixel(selectedIdx, x, y);
    }

    public void SetPixel(int index, int x, int y)
    {
        if (x < 0 || x >= width || y < 0 || y >= height) return;
        img[x, y] = index;
    }

    public Texture2D ExportToTexture2D()
    {
        Texture2D texture = new Texture2D(width, height);
        texture.filterMode = FilterMode.Point;

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                texture.SetPixel(x, y, palette[img[x, y]]);
            }
        }
        
        texture.Apply();

        return texture;
    }
}